package com.hr.user.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.hr.rbac.domain.Role;
import com.hr.rbac.service.RBACService;
import com.hr.user.domain.User;
import com.hr.user.service.Impl.UserServiceImpl;
import com.hr.utils.BaseServlet;

public class UserLoginServlet extends BaseServlet {
	
	private UserServiceImpl userServiceImpl = new UserServiceImpl();
	private RBACService rbacService = new RBACService();
	/**
	 * 实现用户登陆的基础功能
	 * @param request
	 * @param response
	 * @return
	 * @throws ServletException
	 * @throws IOException
	 */
	public String login(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		String verfiyCode = (String)session.getAttribute("VerifyCode");
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		
		String verifyCode_jsp = request.getParameter("verifyCode");
		
		if(verifyCode_jsp.equalsIgnoreCase(verfiyCode)){
			User user_find = userServiceImpl.login(user);
			if(user_find!=null){
				session.setAttribute("user", user_find);
				request.setAttribute("msg", "登陆成功");
				if(rbacService.findByUserID(user_find.getUser_id()) != null) {
					request.setAttribute("role", rbacService.findByUserID(user_find.getUser_id()));
				} else {
					Role role = null;
					request.setAttribute("role", role);
				}
				
				return "f:/manage/index.jsp";
			} else {
				request.setAttribute("msg", "登陆名或密码错误，请重新登陆");
			}
		} else {
			request.setAttribute("msg", "验证码输入错误，请重新输入");
			return "f:/manage/login.jsp";
		}
		return "f:/manage/login.jsp";
	}
}
